<template>
    <div class="user-operation-container">
        <!-- 查询条件区域 -->
        <div class="query-section">
            <el-card class="query-card">
                <template #header>
                    <div class="card-header">
                        <span>用户信息查询</span>
                    </div>
                </template>

                <el-form :model="queryForm" :inline="true" class="query-form">
                    <el-form-item label="账户">
                        <el-input v-model="queryForm.account" placeholder="请输入账户名称" clearable style="width: 200px" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleQuery" :loading="loading">
                            <el-icon>
                                <Search />
                            </el-icon>
                            查询
                        </el-button>
                        <el-button @click="handleReset">
                            <el-icon>
                                <Refresh />
                            </el-icon>
                            重置
                        </el-button>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>

        <!-- 数据展示区域 -->
        <div class="data-section">
            <el-card class="data-card">
                <template #header>
                    <div class="card-header">
                        <span>用户信息列表</span>
                        <div class="header-actions">
                            <el-button type="success" @click="handleAdd">
                                <el-icon>
                                    <Plus />
                                </el-icon>
                                新增用户
                            </el-button>
                            <el-button type="danger" @click="handleBatchDelete" :disabled="selectedUsers.length === 0"
                                :loading="batchDeleteLoading">
                                <el-icon>
                                    <Delete />
                                </el-icon>
                                批量删除 ({{ selectedUsers.length }})
                            </el-button>
                            <el-button type="primary" @click="handleExport" :loading="exportLoading">
                                <el-icon>
                                    <Download />
                                </el-icon>
                                导出数据
                            </el-button>
                            <el-button type="success" @click="handleImport">
                                <el-icon>
                                    <Upload />
                                </el-icon>
                                导入
                            </el-button>
                            <el-button type="info" @click="handleColumnSettings">
                                <el-icon>
                                    <Setting />
                                </el-icon>
                                列设置
                            </el-button>

                        </div>
                    </div>
                </template>

                <!-- 数据表格 -->
                <el-table class="compact-table" :data="userList" v-loading="loading" stripe border size="small"
                    style="width: 100%" :scrollbar-always-on="true" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="45" align="center" />

                    <!-- 动态列渲染 -->
                    <template v-for="col in getVisibleColumns()" :key="col.key">
                        <!-- 账号列 -->
                        <el-table-column v-if="col.key === 'Account'" prop="Account" :label="col.label" width="120"
                            sortable>
                            <template #default="scope">
                                <span class="account-text">{{ scope.row.Account }}</span>
                            </template>
                        </el-table-column>

                        <!-- 姓名列 -->
                        <el-table-column v-if="col.key === 'Name'" prop="Name" :label="col.label" width="120" />

                        <!-- 性别列 -->
                        <el-table-column v-if="col.key === 'Gender'" prop="Gender" :label="col.label" width="80"
                            align="center">
                            <template #default="scope">
                                <el-tag :type="scope.row.Gender === '男' ? 'primary' : 'success'" size="small">
                                    {{ scope.row.Gender }}
                                </el-tag>
                            </template>
                        </el-table-column>

                        <!-- 头像列 -->
                        <el-table-column v-if="col.key === 'Avatar'" prop="Avatar" :label="col.label" width="100"
                            align="center">
                            <template #default="scope">
                                <el-avatar
                                    v-if="scope.row.Avatar && scope.row.Avatar !== '//' && scope.row.Avatar !== '' && scope.row.Avatar !== 'string' && scope.row.Avatar.startsWith('/image/')"
                                    :src="getImageUrl(scope.row.Avatar)" :size="40"
                                    @error="(e: Event) => handleImageError(e, scope.row.Avatar)" />
                                <el-avatar v-else :size="40" icon="UserFilled" />
                            </template>
                        </el-table-column>

                        <!-- 角色列 -->
                        <el-table-column v-if="col.key === 'Role'" prop="Role" :label="col.label" width="120"
                            align="center">
                            <template #default="scope">
                                <el-tag type="info" size="small">{{ scope.row.Role }}</el-tag>
                            </template>
                        </el-table-column>

                        <!-- 注册时间列 -->
                        <el-table-column v-if="col.key === 'CreateTime'" prop="CreateTime" :label="col.label"
                            width="180" sortable>
                            <template #default="scope">
                                {{ formatDateTime(scope.row.CreateTime) }}
                            </template>
                        </el-table-column>

                        <!-- 创建人列 -->
                        <el-table-column v-if="col.key === 'Creator'" prop="Creator" :label="col.label" width="120">
                            <template #default="scope">
                                {{ scope.row.Creator || '系统' }}
                            </template>
                        </el-table-column>

                        <!-- 是否可用列 -->
                        <el-table-column v-if="col.key === 'IsActive'" prop="IsActive" :label="col.label" width="100"
                            align="center">
                            <template #default="scope">
                                <el-tag :type="scope.row.IsActive ? 'success' : 'danger'" size="small">
                                    {{ scope.row.IsActive ? '是' : '否' }}
                                </el-tag>
                            </template>
                        </el-table-column>

                        <!-- 单选钮列 -->
                        <el-table-column v-if="col.key === 'SingleSelectButton'" prop="SingleSelectButton"
                            :label="col.label" width="100" align="center">
                            <template #default="scope">
                                <el-tag :type="scope.row.SingleSelectButton ? 'success' : 'info'" size="small">
                                    {{ scope.row.SingleSelectButton ? '是' : '否' }}
                                </el-tag>
                            </template>
                        </el-table-column>

                        <!-- 复选框(公牛)列 -->
                        <el-table-column v-if="col.key === 'CheckboxBull'" prop="CheckboxBull" :label="col.label"
                            width="100" align="center">
                            <template #default="scope">
                                <el-tag :type="scope.row.CheckboxBull ? 'warning' : 'info'" size="small">
                                    {{ scope.row.CheckboxBull ? '公牛' : '否' }}
                                </el-tag>
                            </template>
                        </el-table-column>

                        <!-- 时间列 -->
                        <el-table-column v-if="col.key === 'Time'" prop="Time" :label="col.label" width="120"
                            align="center">
                            <template #default="scope">
                                {{ formatTime(scope.row.Time) }}
                            </template>
                        </el-table-column>

                        <!-- 日期列 -->
                        <el-table-column v-if="col.key === 'Date'" prop="Date" :label="col.label" width="120"
                            align="center">
                            <template #default="scope">
                                {{ formatDate(scope.row.Date) }}
                            </template>
                        </el-table-column>

                        <!-- 小数列 -->
                        <el-table-column v-if="col.key === 'DecimalValue'" prop="DecimalValue" :label="col.label"
                            width="100" align="center">
                            <template #default="scope">
                                {{ scope.row.DecimalValue || '-' }}
                            </template>
                        </el-table-column>

                        <!-- 文本域列 -->
                        <el-table-column v-if="col.key === 'TextArea'" prop="TextArea" :label="col.label" width="150">
                            <template #default="scope">
                                <el-tooltip :content="scope.row.TextArea || '无'" placement="top">
                                    <span class="text-truncate">{{ scope.row.TextArea || '无' }}</span>
                                </el-tooltip>
                            </template>
                        </el-table-column>

                        <!-- 图片列 -->
                        <el-table-column v-if="col.key === 'Image'" prop="Image" :label="col.label" width="100"
                            align="center">
                            <template #default="scope">
                                <el-image
                                    v-if="scope.row.Image && scope.row.Image !== '//' && scope.row.Image !== '' && scope.row.Image !== 'string' && scope.row.Image.startsWith('/image/')"
                                    :src="getImageUrl(scope.row.Image)"
                                    :preview-src-list="[getImageUrl(scope.row.Image)]"
                                    style="width: 40px; height: 40px; border-radius: 4px;" :preview-teleported="true"
                                    @error="handleImageError">
                                    <template #error>
                                        <div class="image-error">
                                            <el-icon>
                                                <Picture />
                                            </el-icon>
                                            <span>加载失败</span>
                                        </div>
                                    </template>
                                </el-image>
                                <div v-else class="image-placeholder">
                                    <el-icon>
                                        <Picture />
                                    </el-icon>
                                    <span>无图片</span>
                                </div>
                            </template>
                        </el-table-column>

                        <!-- QQ号码2列 -->
                        <el-table-column v-if="col.key === 'QQNumber2'" prop="QQNumber2" :label="col.label" width="120"
                            align="center">
                            <template #default="scope">
                                {{ scope.row.QQNumber2 || '-' }}
                            </template>
                        </el-table-column>

                        <!-- QQ号码1列 -->
                        <el-table-column v-if="col.key === 'QQNumber1'" prop="QQNumber1" :label="col.label" width="120"
                            align="center">
                            <template #default="scope">
                                {{ scope.row.QQNumber1 || '-' }}
                            </template>
                        </el-table-column>

                        <!-- 测试列 -->
                        <el-table-column v-if="col.key === 'Test'" prop="Test" :label="col.label" width="100"
                            align="center">
                            <template #default="scope">
                                {{ scope.row.Test || '-' }}
                            </template>
                        </el-table-column>

                        <!-- 测试1列 -->
                        <el-table-column v-if="col.key === 'Test1'" prop="Test1" :label="col.label" width="100"
                            align="center">
                            <template #default="scope">
                                {{ scope.row.Test1 || '-' }}
                            </template>
                        </el-table-column>
                    </template>

                    <el-table-column label="操作" width="120" align="center" fixed="right">
                        <template #default="scope">
                            <el-button type="primary" size="small" @click="handleEdit(scope.row)">
                                编辑
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>



                <!-- 空数据状态 -->
                <div class="empty-data" v-if="!loading && pagination.total === 0">
                    <el-empty description="暂无数据" :image-size="100">
                        <el-button type="primary" @click="handleReset">重新加载</el-button>
                    </el-empty>
                </div>

                <!-- 分页组件 -->
                <div class="pagination-container" v-if="pagination.total > 0">
                    <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                        :page-sizes="[10, 20, 50, 100]" :total="pagination.total"
                        layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" :hide-on-single-page="false" :background="true" small />
                </div>
            </el-card>
        </div>

        <!-- 新增用户弹框 -->
        <el-dialog v-model="addDialogVisible" title="新增用户" width="800px" :close-on-click-modal="false"
            :close-on-press-escape="false">
            <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="120px" label-position="left">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="账户" prop="account">
                            <el-input v-model="addForm.account" placeholder="请输入账户名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="密码" prop="pwd">
                            <el-input v-model="addForm.pwd" type="password" placeholder="请输入密码" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="姓名" prop="name">
                            <el-input v-model="addForm.name" placeholder="请输入姓名" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="性别" prop="gender">
                            <el-select v-model="addForm.gender" placeholder="请选择性别" style="width: 100%" clearable>
                                <el-option label="男" value="男" />
                                <el-option label="女" value="女" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="角色" prop="role">
                            <el-input v-model="addForm.role" placeholder="请输入角色" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="组织架构" prop="organizationStructure">
                            <el-input v-model="addForm.organizationStructure" placeholder="请输入组织架构" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="状态" prop="isActive">
                            <el-switch v-model="addForm.isActive" active-text="启用" inactive-text="禁用" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="单选钮" prop="singleSelectButton">
                            <el-switch v-model="addForm.singleSelectButton" active-text="是" inactive-text="否" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="复选框(公牛)" prop="checkboxBull">
                            <el-switch v-model="addForm.checkboxBull" active-text="是" inactive-text="否" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="复选框(母牛)" prop="checkboxCow">
                            <el-switch v-model="addForm.checkboxCow" active-text="是" inactive-text="否" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="时间" prop="time">
                            <el-time-picker v-model="addForm.time" placeholder="选择时间" style="width: 100%"
                                format="HH:mm:ss" value-format="HH:mm:ss" :clearable="true" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="日期" prop="date">
                            <el-date-picker v-model="addForm.date" type="date" placeholder="选择日期" style="width: 100%"
                                format="YYYY-MM-DD" value-format="YYYY-MM-DD" :clearable="true" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="小数" prop="decimalValue">
                            <el-input-number v-model="addForm.decimalValue" :precision="2" :step="0.1" :min="0"
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="号码1" prop="qqNumber1">
                            <el-input v-model="addForm.qqNumber1" placeholder="请输入号码1" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="号码2" prop="qqNumber2">
                            <el-input v-model="addForm.qqNumber2" placeholder="请输入号码2" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="测试" prop="test">
                            <el-input v-model="addForm.test" placeholder="请输入测试字段" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="测试1" prop="test1">
                            <el-input v-model="addForm.test1" placeholder="请输入测试1字段" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="addForm.remark" placeholder="请输入备注" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="文本域" prop="textArea">
                    <el-input v-model="addForm.textArea" type="textarea" :rows="3" placeholder="请输入文本域内容" />
                </el-form-item>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="头像" prop="avatar">
                            <div class="upload-container">
                                <el-upload ref="avatarUploadRef" :action="uploadImageUrl" :headers="uploadHeaders"
                                    :show-file-list="false" :on-success="handleAvatarSuccess"
                                    :on-error="handleUploadError" :before-upload="beforeAvatarUpload" accept="image/*"
                                    name="imageFile">
                                    <el-avatar
                                        v-if="addForm.avatar && addForm.avatar !== 'string' && addForm.avatar.startsWith('/image/')"
                                        :src="getImageUrl(addForm.avatar)" :size="80" class="upload-avatar" />
                                    <div v-else class="upload-placeholder">
                                        <el-icon>
                                            <Picture />
                                        </el-icon>
                                        <span>上传头像</span>
                                    </div>
                                </el-upload>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="图片" prop="image">
                            <div class="upload-container">
                                <el-upload ref="imageUploadRef" :action="uploadImageUrl" :headers="uploadHeaders"
                                    :show-file-list="false" :on-success="handleImageSuccess"
                                    :on-error="handleUploadError" :before-upload="beforeImageUpload" accept="image/*"
                                    name="imageFile">
                                    <el-image
                                        v-if="addForm.image && addForm.image !== 'string' && addForm.image.startsWith('/image/')"
                                        :src="getImageUrl(addForm.image)"
                                        style="width: 80px; height: 80px; border-radius: 4px;" fit="cover"
                                        class="upload-image" />
                                    <div v-else class="upload-placeholder">
                                        <el-icon>
                                            <Picture />
                                        </el-icon>
                                        <span>上传图片</span>
                                    </div>
                                </el-upload>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleCancel">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 编辑用户弹框 -->
        <el-dialog v-model="editDialogVisible" title="编辑用户" width="800px" :close-on-click-modal="false"
            :close-on-press-escape="false">
            <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="120px"
                label-position="left">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="账户" prop="account">
                            <el-input v-model="editForm.account" placeholder="请输入账户名称" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="密码" prop="pwd">
                            <el-input v-model="editForm.pwd" type="password" placeholder="请输入密码" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="姓名" prop="name">
                            <el-input v-model="editForm.name" placeholder="请输入姓名" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="性别" prop="gender">
                            <el-select v-model="editForm.gender" placeholder="请选择性别" style="width: 100%" clearable>
                                <el-option label="男" value="男" />
                                <el-option label="女" value="女" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="角色" prop="role">
                            <el-input v-model="editForm.role" placeholder="请输入角色" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="组织架构" prop="organizationStructure">
                            <el-input v-model="editForm.organizationStructure" placeholder="请输入组织架构" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="状态" prop="isActive">
                            <el-switch v-model="editForm.isActive" active-text="启用" inactive-text="禁用" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="单选钮" prop="singleSelectButton">
                            <el-switch v-model="editForm.singleSelectButton" active-text="是" inactive-text="否" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="复选框(公牛)" prop="checkboxBull">
                            <el-switch v-model="editForm.checkboxBull" active-text="是" inactive-text="否" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="复选框(母牛)" prop="checkboxCow">
                            <el-switch v-model="editForm.checkboxCow" active-text="是" inactive-text="否" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="时间" prop="time">
                            <el-time-picker v-model="editForm.time" placeholder="选择时间" style="width: 100%"
                                format="HH:mm:ss" value-format="HH:mm:ss" :clearable="true" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="日期" prop="date">
                            <el-date-picker v-model="editForm.date" type="date" placeholder="选择日期" style="width: 100%"
                                format="YYYY-MM-DD" value-format="YYYY-MM-DD" :clearable="true" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="小数" prop="decimalValue">
                            <el-input-number v-model="editForm.decimalValue" :precision="2" :step="0.1" :min="0"
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="号码1" prop="qqNumber1">
                            <el-input v-model="editForm.qqNumber1" placeholder="请输入号码1" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="号码2" prop="qqNumber2">
                            <el-input v-model="editForm.qqNumber2" placeholder="请输入号码2" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="测试" prop="test">
                            <el-input v-model="editForm.test" placeholder="请输入测试字段" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="测试1" prop="test1">
                            <el-input v-model="editForm.test1" placeholder="请输入测试1字段" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="editForm.remark" placeholder="请输入备注" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="文本域" prop="textArea">
                    <el-input v-model="editForm.textArea" type="textarea" :rows="3" placeholder="请输入文本域内容" />
                </el-form-item>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="头像" prop="avatar">
                            <div class="upload-container">
                                <el-upload ref="editAvatarUploadRef" :action="uploadImageUrl" :headers="uploadHeaders"
                                    :show-file-list="false" :on-success="handleAvatarSuccess"
                                    :on-error="handleUploadError" :before-upload="beforeAvatarUpload" accept="image/*"
                                    name="imageFile">
                                    <el-avatar
                                        v-if="editForm.avatar && editForm.avatar !== 'string' && editForm.avatar.startsWith('/image/')"
                                        :src="getImageUrl(editForm.avatar)" :size="80" class="upload-avatar" />
                                    <div v-else class="upload-placeholder">
                                        <el-icon>
                                            <Picture />
                                        </el-icon>
                                        <span>上传头像</span>
                                    </div>
                                </el-upload>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="图片" prop="image">
                            <div class="upload-container">
                                <el-upload ref="editImageUploadRef" :action="uploadImageUrl" :headers="uploadHeaders"
                                    :show-file-list="false" :on-success="handleImageSuccess"
                                    :on-error="handleUploadError" :before-upload="beforeImageUpload" accept="image/*"
                                    name="imageFile">
                                    <el-image
                                        v-if="editForm.image && editForm.image !== 'string' && editForm.image.startsWith('/image/')"
                                        :src="getImageUrl(editForm.image)"
                                        style="width: 80px; height: 80px; border-radius: 4px;" fit="cover"
                                        class="upload-image" />
                                    <div v-else class="upload-placeholder">
                                        <el-icon>
                                            <Picture />
                                        </el-icon>
                                        <span>上传图片</span>
                                    </div>
                                </el-upload>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleEditCancel">取消</el-button>
                    <el-button type="primary" @click="handleEditSubmit" :loading="editLoading">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 导入用户弹框 -->
        <el-dialog v-model="importDialogVisible" title="用户管理-导入" width="600px" :close-on-click-modal="false"
            @close="closeImportDialog">
            <div class="import-container">
                <!-- 文件上传区域 -->
                <div class="upload-area">
                    <div class="upload-buttons">
                        <el-button @click="downloadTemplate">
                            <el-icon>
                                <Download />
                            </el-icon>
                            下载模板
                        </el-button>
                        <el-button type="primary" @click="triggerFileSelect">
                            <el-icon>
                                <Folder />
                            </el-icon>
                            选择文件
                        </el-button>
                        <el-button type="success" @click="uploadFile" :loading="importLoading" :disabled="!importFile">
                            <el-icon>
                                <Upload />
                            </el-icon>
                            上传文件
                        </el-button>
                    </div>

                    <!-- 隐藏的文件输入 -->
                    <input id="fileInput" type="file" accept=".xlsx,.xls" style="display: none"
                        @change="handleFileSelect" />

                    <!-- 文件信息显示 -->
                    <div v-if="importFile" class="file-info">
                        <el-icon>
                            <Document />
                        </el-icon>
                        <span>{{ importFile.name }}</span>
                        <span class="file-size">({{ (importFile.size / 1024 / 1024).toFixed(2) }}MB)</span>
                    </div>
                </div>

                <!-- 上传说明 -->
                <el-alert title="上传说明" type="warning" :closable="false" show-icon style="margin: 20px 0">
                    <template #default>
                        <p>只能上传excel文件，文件大小不超过100M</p>
                    </template>
                </el-alert>

                <!-- 导入结果 -->
                <div v-if="importResult" class="import-result">
                    <el-alert :title="importResult.Success ? '导入成功' : '导入失败'"
                        :type="importResult.Success ? 'success' : 'error'" :closable="false" show-icon>
                        <template #default>
                            <div class="result-details">
                                <p><strong>总数量:</strong> {{ importResult.TotalCount }}</p>
                                <p><strong>成功导入:</strong> <span class="success-count">{{ importResult.SuccessCount
                                }}</span></p>
                                <p><strong>更新用户:</strong> <span class="update-count">{{ importResult.UpdatedCount
                                }}</span></p>
                                <p><strong>跳过用户:</strong> <span class="skip-count">{{ importResult.SkippedCount
                                }}</span></p>
                                <p><strong>失败用户:</strong> <span class="failed-count">{{ importResult.FailedCount
                                }}</span></p>
                            </div>
                        </template>
                    </el-alert>
                </div>
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="closeImportDialog">
                        <el-icon>
                            <Close />
                        </el-icon>
                        关闭
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 列设置弹框 -->
        <el-dialog v-model="columnSettingsVisible" title="列设置" width="600px" :close-on-click-modal="false">
            <el-alert title="拖动列名可调整表格列显示顺序" type="success" :closable="false" show-icon style="margin-bottom: 20px" />

            <el-table :data="columnSettings.columns" style="width: 100%">
                <el-table-column prop="order" label="#" width="60" align="center" />
                <el-table-column prop="label" label="列名" />
                <el-table-column label="是否显示" width="100" align="center">
                    <template #default="scope">
                        <el-checkbox v-model="scope.row.visible" />
                    </template>
                </el-table-column>
            </el-table>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="columnSettingsVisible = false">
                        <el-icon>
                            <Close />
                        </el-icon>
                        取消
                    </el-button>
                    <el-button type="success" @click="resetColumnSettings">
                        <el-icon>
                            <Refresh />
                        </el-icon>
                        重置
                    </el-button>
                    <el-button type="primary" @click="confirmColumnSettings">
                        <el-icon>
                            <Check />
                        </el-icon>
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Picture, Delete, Download, Setting, Close, Check, Upload, Folder, Document } from '@element-plus/icons-vue'
import { MES_XHY_ApiHost } from '@/utils/Interceptors'

// 用户信息接口类型定义
interface UserInfo {
    Id: number
    Account: string
    Pwd: string
    Name: string
    Role: string
    IsActive: boolean
    OrganizationStructure: string
    Remark: string
    Avatar: string
    Gender: string
    SingleSelectButton: boolean
    CheckboxBull: boolean
    CheckboxCow: boolean
    Time: string
    Date: string
    DecimalValue: number
    TextArea: string
    Image: string
    QQNumber1: string | null
    QQNumber2: string
    Test: string | null
    Test1: string | null
    CreateTime: string
    IsDelete: boolean
    Creator?: string
}

// 查询表单
const queryForm = reactive({
    account: ''
})



// 分页配置
const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
})

// 数据列表
const userList = ref<UserInfo[]>([])
const allUserList = ref<UserInfo[]>([]) // 存储所有用户数据
const loading = ref(false)

// 新增用户相关
const addDialogVisible = ref(false)
const submitLoading = ref(false)
const addFormRef = ref()
const avatarUploadRef = ref()
const imageUploadRef = ref()

// 编辑用户相关
const editDialogVisible = ref(false)
const editLoading = ref(false)
const editFormRef = ref()
const editAvatarUploadRef = ref()
const editImageUploadRef = ref()

// 批量删除相关
const selectedUsers = ref<UserInfo[]>([])
const batchDeleteLoading = ref(false)

// 导出相关
const exportLoading = ref(false)

// 导入相关
const importDialogVisible = ref(false)
const importLoading = ref(false)
const importFile = ref<File | null>(null)
const importResult = ref<any>(null)

// 列设置相关
const columnSettingsVisible = ref(false)
const columnSettings = reactive({
    columns: [
        { key: 'Account', label: '账号', visible: true, order: 1 },
        { key: 'Name', label: '姓名', visible: true, order: 2 },
        { key: 'Gender', label: '性别', visible: true, order: 3 },
        { key: 'Avatar', label: '头像', visible: true, order: 4 },
        { key: 'Role', label: '角色', visible: true, order: 5 },
        { key: 'CreateTime', label: '注册时间', visible: true, order: 6 },
        { key: 'Creator', label: '创建人', visible: true, order: 7 },
        { key: 'IsActive', label: '是否可用', visible: true, order: 8 },
        { key: 'SingleSelectButton', label: '单选钮', visible: true, order: 9 },
        { key: 'CheckboxBull', label: '复选框', visible: true, order: 10 },
        { key: 'Time', label: '时间', visible: true, order: 11 },
        { key: 'Date', label: '日期', visible: true, order: 12 },
        { key: 'DecimalValue', label: '小数', visible: true, order: 13 },
        { key: 'TextArea', label: '文本域', visible: true, order: 14 },
        { key: 'Image', label: '图片', visible: true, order: 15 },
        { key: 'QQNumber2', label: '号码2', visible: true, order: 16 },
        { key: 'QQNumber1', label: '号码1', visible: true, order: 17 },
        { key: 'Test', label: '测试', visible: true, order: 18 },
        { key: 'Test1', label: '测试1', visible: true, order: 19 }
    ]
})

// 默认列设置（用于重置）
const defaultColumnSettings = JSON.parse(JSON.stringify(columnSettings.columns))

// 新增表单数据
const addForm = reactive({
    account: '',
    pwd: '',
    name: '',
    role: '',
    isActive: true,
    organizationStructure: '',
    remark: '',
    avatar: '',
    gender: '',
    singleSelectButton: true,
    checkboxBull: true,
    checkboxCow: true,
    time: '',
    date: '',
    decimalValue: 0,
    textArea: '',
    image: '',
    qqNumber2: '',
    qqNumber1: '',
    test: '',
    test1: ''
})

// 编辑表单数据
const editForm = reactive({
    id: 0,
    account: '',
    pwd: '',
    name: '',
    role: '',
    isActive: true,
    organizationStructure: '',
    remark: '',
    avatar: '',
    gender: '',
    singleSelectButton: true,
    checkboxBull: true,
    checkboxCow: true,
    time: '',
    date: '',
    decimalValue: 0,
    textArea: '',
    image: '',
    qqNumber2: '',
    qqNumber1: '',
    test: '',
    test1: ''
})

// 表单验证规则
const addFormRules = {
    account: [
        { required: true, message: '请输入账户名称', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    pwd: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
    ],
    role: [
        { required: true, message: '请输入角色', trigger: 'blur' }
    ],
    gender: [
        { required: true, message: '请选择性别', trigger: 'change' }
    ],
    organizationStructure: [
        { required: false, message: '请输入组织架构', trigger: 'blur' }
    ],
    remark: [
        { required: false, message: '请输入备注', trigger: 'blur' }
    ],
    time: [
        { required: false, message: '请选择时间', trigger: 'change' }
    ],
    date: [
        { required: false, message: '请选择日期', trigger: 'change' }
    ]
}

// 编辑表单验证规则
const editFormRules = {
    account: [
        { required: true, message: '请输入账户名称', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    pwd: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
    ],
    role: [
        { required: true, message: '请输入角色', trigger: 'blur' }
    ],
    gender: [
        { required: true, message: '请选择性别', trigger: 'change' }
    ],
    organizationStructure: [
        { required: false, message: '请输入组织架构', trigger: 'blur' }
    ],
    remark: [
        { required: false, message: '请输入备注', trigger: 'blur' }
    ],
    time: [
        { required: false, message: '请选择时间', trigger: 'change' }
    ],
    date: [
        { required: false, message: '请选择日期', trigger: 'change' }
    ]
}

// 上传相关配置
const uploadImageUrl = `${MES_XHY_ApiHost.defaults.baseURL}/api/Login/uploadImage`
const uploadHeaders = {
    Authorization: `Bearer ${localStorage.getItem('token') || ''}`
}

// 获取用户列表
const getUserList = async () => {
    try {
        loading.value = true

        // 如果是第一次加载或者有查询条件，则从后端获取数据
        if (allUserList.value.length === 0 || queryForm.account) {
            const params = {
                account: queryForm.account || undefined
            }

            const response = await MES_XHY_ApiHost.get('/api/Login/getAllUsers', { params })

            if (response.data.code === 200) {
                // 检查返回的数据结构
                if (response.data.data && Array.isArray(response.data.data)) {
                    allUserList.value = response.data.data
                } else if (response.data.data && response.data.data.items && Array.isArray(response.data.data.items)) {
                    allUserList.value = response.data.data.items
                } else {
                    allUserList.value = []
                }

                console.log(`从后端获取到 ${allUserList.value.length} 条用户数据`)
            } else {
                ElMessage.error(response.data.msg || '查询失败')
                allUserList.value = []
                userList.value = []
                pagination.total = 0
                console.warn('API返回错误:', response.data)
                return
            }
        }

        // 实现前端分页逻辑
        applyFrontendPagination()

    } catch (error) {
        console.error('获取用户列表失败:', error)

        // 处理网络错误
        if (error && typeof error === 'object' && 'code' in error) {
            if (error.code === 'NETWORK_ERROR') {
                ElMessage.error('网络连接失败，请检查网络设置')
            } else if (error.code === 'TIMEOUT') {
                ElMessage.error('请求超时，请稍后重试')
            } else {
                ElMessage.error('获取用户列表失败，请稍后重试')
            }
        } else {
            ElMessage.error('获取用户列表失败，请稍后重试')
        }

        allUserList.value = []
        userList.value = []
        pagination.total = 0
    } finally {
        loading.value = false
    }
}

// 前端分页逻辑
const applyFrontendPagination = () => {
    if (allUserList.value.length === 0) {
        userList.value = []
        pagination.total = 0
        console.log('前端分页: 没有数据可显示')
        return
    }

    // 计算总数
    pagination.total = allUserList.value.length

    // 计算当前页应该显示的数据
    const startIndex = (pagination.currentPage - 1) * pagination.pageSize
    const endIndex = startIndex + pagination.pageSize

    // 获取当前页的数据
    userList.value = allUserList.value.slice(startIndex, endIndex)

    console.log(`前端分页: 当前页 ${pagination.currentPage}, 每页 ${pagination.pageSize}, 总数 ${pagination.total}`)
    console.log(`显示数据: 第 ${startIndex + 1} - ${Math.min(endIndex, pagination.total)} 条`)
    console.log(`当前页数据条数: ${userList.value.length}`)
    console.log(`分页计算: startIndex=${startIndex}, endIndex=${endIndex}`)

    // 验证分页逻辑
    const totalPages = Math.ceil(pagination.total / pagination.pageSize)
    console.log(`总页数: ${totalPages}`)

    if (pagination.currentPage > totalPages && totalPages > 0) {
        console.warn(`当前页 ${pagination.currentPage} 超出总页数 ${totalPages}，自动调整到最后一页`)
        pagination.currentPage = totalPages
        // 重新计算当前页数据
        const newStartIndex = (pagination.currentPage - 1) * pagination.pageSize
        const newEndIndex = newStartIndex + pagination.pageSize
        userList.value = allUserList.value.slice(newStartIndex, newEndIndex)
        console.log(`调整后显示数据: 第 ${newStartIndex + 1} - ${Math.min(newEndIndex, pagination.total)} 条`)
    }
}

// 查询操作
const handleQuery = () => {
    console.log('执行查询操作')
    pagination.currentPage = 1 // 查询时重置到第一页
    // 清空缓存的数据，重新从后端获取
    allUserList.value = []
    getUserList()
}

// 重置查询条件
const handleReset = () => {
    console.log('重置查询条件')
    queryForm.account = ''
    pagination.currentPage = 1 // 重置时回到第一页
    // 清空缓存的数据，重新从后端获取
    allUserList.value = []
    getUserList()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
    console.log(`分页大小改变: ${size}`)

    // 验证分页大小的有效性
    if (size < 1) {
        console.warn('分页大小不能小于1，重置为10')
        pagination.pageSize = 10
    } else if (size > 1000) {
        console.warn('分页大小不能大于1000，重置为100')
        pagination.pageSize = 100
    } else {
        pagination.pageSize = size
    }

    pagination.currentPage = 1 // 重置到第一页
    console.log('分页配置更新:', { pageSize: pagination.pageSize, currentPage: pagination.currentPage })

    // 直接应用前端分页，不需要重新请求后端
    applyFrontendPagination()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
    console.log(`当前页改变: ${page}`)

    // 验证页码的有效性
    if (page < 1) {
        console.warn('页码不能小于1，重置为1')
        pagination.currentPage = 1
    } else if (pagination.total > 0) {
        const maxPage = Math.ceil(pagination.total / pagination.pageSize)
        if (page > maxPage) {
            console.warn(`页码不能大于最大页数 ${maxPage}，重置为 ${maxPage}`)
            pagination.currentPage = maxPage
        } else {
            pagination.currentPage = page
        }
    } else {
        pagination.currentPage = page
    }

    console.log('分页配置更新:', { pageSize: pagination.pageSize, currentPage: pagination.currentPage })

    // 直接应用前端分页，不需要重新请求后端
    applyFrontendPagination()
}

// 新增用户
const handleAdd = () => {
    addDialogVisible.value = true
    resetAddForm()
}

// 重置新增表单
const resetAddForm = () => {
    Object.assign(addForm, {
        account: '',
        pwd: '',
        name: '',
        role: '',
        isActive: true,
        organizationStructure: '',
        remark: '',
        avatar: '',
        gender: '',
        singleSelectButton: true,
        checkboxBull: true,
        checkboxCow: true,
        time: '',
        date: '',
        decimalValue: 0,
        textArea: '',
        image: '',
        qqNumber2: '',
        qqNumber1: '',
        test: '',
        test1: ''
    })
    if (addFormRef.value) {
        addFormRef.value.clearValidate()
    }
}

// 取消新增
const handleCancel = () => {
    addDialogVisible.value = false
    resetAddForm()
}

// 提交新增
const handleSubmit = async () => {
    try {
        // 先验证表单
        await addFormRef.value.validate()

        // 手动验证必填字段
        if (!addForm.account || addForm.account.trim() === '') {
            ElMessage.error('账户不能为空')
            return
        }
        if (!addForm.pwd || addForm.pwd.trim() === '') {
            ElMessage.error('密码不能为空')
            return
        }
        if (!addForm.name || addForm.name.trim() === '') {
            ElMessage.error('姓名不能为空')
            return
        }
        if (!addForm.role || addForm.role.trim() === '') {
            ElMessage.error('角色不能为空')
            return
        }
        if (!addForm.gender || addForm.gender.trim() === '') {
            ElMessage.error('性别不能为空')
            return
        }

        submitLoading.value = true

        // 准备提交的数据，确保所有字段都有值
        const userData = {
            Account: addForm.account?.trim() || '',           // 首字母大写，匹配后端期望，并去除空格
            Pwd: addForm.pwd?.trim() || '',                  // 首字母大写，匹配后端期望，并去除空格
            Name: addForm.name?.trim() || '',                // 首字母大写，匹配后端期望，并去除空格
            Role: addForm.role?.trim() || '',                // 首字母大写，匹配后端期望，并去除空格
            IsActive: addForm.isActive,        // 首字母大写，匹配后端期望
            OrganizationStructure: addForm.organizationStructure?.trim() || '',
            Remark: addForm.remark?.trim() || '',
            Avatar: addForm.avatar?.trim() || '',
            Gender: addForm.gender?.trim() || '',
            SingleSelectButton: addForm.singleSelectButton,
            CheckboxBull: addForm.checkboxBull,
            CheckboxCow: addForm.checkboxCow,
            Time: formatTimeForSubmit(addForm.time), // 格式化时间
            Date: formatDateForSubmit(addForm.date), // 格式化日期
            DecimalValue: addForm.decimalValue || 0,
            TextArea: addForm.textArea?.trim() || '',
            Image: addForm.image?.trim() || '',
            QQNumber2: addForm.qqNumber2?.trim() || '',      // 修正：QQNumber2 应该是 QQNumber2
            QQNumber1: addForm.qqNumber1?.trim() || '',      // 修正：QQNumber1 应该是 QQNumber1
            Test: addForm.test?.trim() || '',
            Test1: addForm.test1?.trim() || ''
        }

        // 按照后端期望的格式包装数据
        const submitData = {
            userAddDTO: userData
        }

        // 尝试不同的数据格式
        const alternativeSubmitData = userData  // 直接提交userData，不包装

        // 验证关键字段
        console.log('=== 提交前验证 ===')
        console.log('表单原始数据:', addForm)
        console.log('账户值:', userData.Account, '类型:', typeof userData.Account, '是否为空:', !userData.Account, '长度:', userData.Account?.length)
        console.log('密码值:', userData.Pwd, '类型:', typeof userData.Pwd, '是否为空:', !userData.Pwd, '长度:', userData.Pwd?.length)
        console.log('姓名值:', userData.Name, '类型:', typeof userData.Name, '是否为空:', !userData.Name, '长度:', userData.Name?.length)
        console.log('角色值:', userData.Role, '类型:', typeof userData.Role, '是否为空:', !userData.Role, '长度:', userData.Role?.length)
        console.log('性别值:', userData.Gender, '类型:', typeof userData.Gender, '是否为空:', !userData.Gender, '长度:', userData.Gender?.length)
        console.log('完整用户数据:', userData)
        console.log('最终提交数据:', submitData)
        console.log('==================')

        // 最后检查：确保关键字段不为空
        if (!userData.Account || userData.Account.trim() === '') {
            ElMessage.error('账户字段为空，请检查数据绑定')
            return
        }
        if (!userData.Pwd || userData.Pwd.trim() === '') {
            ElMessage.error('密码字段为空，请检查数据绑定')
            return
        }
        if (!userData.Name || userData.Name.trim() === '') {
            ElMessage.error('姓名字段为空，请检查数据绑定')
            return
        }
        if (!userData.Role || userData.Role.trim() === '') {
            ElMessage.error('角色字段为空，请检查数据绑定')
            return
        }

        console.log('✅ 所有必填字段验证通过，开始提交请求...')

        // 先尝试直接提交userData（不包装在userAddDTO中）
        console.log('🔄 尝试直接提交数据格式...')
        let response
        try {
            response = await MES_XHY_ApiHost.post('/api/Login/addUser', alternativeSubmitData)
        } catch (error: any) {
            console.log('直接提交失败，尝试包装格式...')
            // 如果直接提交失败，再尝试包装格式
            response = await MES_XHY_ApiHost.post('/api/Login/addUser', submitData)
        }

        if (response.data.code === 200) {
            ElMessage.success('新增用户成功')
            addDialogVisible.value = false
            resetAddForm()
            // 清空缓存数据，重新获取最新数据
            allUserList.value = []
            getUserList() // 刷新用户列表
        } else {
            ElMessage.error(response.data.msg || '新增用户失败')
        }
    } catch (error: any) {
        console.error('新增用户失败:', error)

        // 处理不同类型的错误
        if (error.response) {
            // 服务器返回了错误响应
            const { status, data } = error.response
            console.error('错误状态:', status, '错误数据:', data)

            if (status === 400) {
                if (data && data.errors) {
                    // 处理验证错误
                    const errorMessages = Object.values(data.errors).flat()
                    ElMessage.error(`数据验证失败: ${errorMessages.join(', ')}`)
                } else if (data && data.title) {
                    ElMessage.error(data.title)
                } else {
                    ElMessage.error('请求数据格式错误，请检查必填字段')
                }
            } else if (status === 401) {
                ElMessage.error('未授权，请重新登录')
            } else if (status === 500) {
                ElMessage.error('服务器内部错误')
            } else {
                ElMessage.error(`请求失败: ${status}`)
            }
        } else if (error.request) {
            // 请求已发出但没有收到响应
            ElMessage.error('网络错误，请检查网络连接')
        } else {
            // 其他错误
            ElMessage.error(error.message || '新增用户失败')
        }
    } finally {
        submitLoading.value = false
    }
}

// 头像上传成功
const handleAvatarSuccess = (response: any) => {
    console.log('头像上传响应:', response)
    if (response.code === 200) {
        // 根据当前激活的弹框更新对应的表单
        if (editDialogVisible.value) {
            editForm.avatar = response.data
        } else {
            addForm.avatar = response.data
        }

        // 调试信息：显示图片URL
        const imageUrl = getImageUrl(response.data)
        console.log('头像路径:', response.data)
        console.log('完整头像URL:', imageUrl)

        ElMessage.success('头像上传成功')
    } else {
        ElMessage.error(response.msg || '头像上传失败')
    }
}

// 图片上传成功
const handleImageSuccess = (response: any) => {
    console.log('图片上传响应:', response)
    if (response.code === 200) {
        // 根据当前激活的弹框更新对应的表单
        if (editDialogVisible.value) {
            editForm.image = response.data
        } else {
            addForm.image = response.data
        }

        // 调试信息：显示图片URL
        const imageUrl = getImageUrl(response.data)
        console.log('图片路径:', response.data)
        console.log('完整图片URL:', imageUrl)

        ElMessage.success('图片上传成功')
    } else {
        ElMessage.error(response.msg || '图片上传失败')
    }
}

// 上传错误处理
const handleUploadError = (error: any, file: any, xhr: any) => {
    console.error('上传失败:', error, file, xhr)

    // 尝试解析错误响应
    let errorMessage = '文件上传失败'
    if (xhr && xhr.responseText) {
        try {
            const errorData = JSON.parse(xhr.responseText)
            if (errorData.errors && errorData.errors.imageFile) {
                errorMessage = errorData.errors.imageFile[0] || '图片文件字段缺失'
            } else if (errorData.title) {
                errorMessage = errorData.title
            }
        } catch (e) {
            console.log('解析错误响应失败:', e)
        }
    }

    ElMessage.error(errorMessage)
}

// 头像上传前验证
const beforeAvatarUpload = (file: File) => {
    const isImage = file.type.startsWith('image/')
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isImage) {
        ElMessage.error('头像只能是图片格式!')
        return false
    }
    if (!isLt2M) {
        ElMessage.error('头像大小不能超过 2MB!')
        return false
    }
    return true
}

// 图片上传前验证
const beforeImageUpload = (file: File) => {
    const isImage = file.type.startsWith('image/')
    const isLt5M = file.size / 1024 / 1024 < 5

    if (!isImage) {
        ElMessage.error('图片只能是图片格式!')
        return false
    }
    if (!isLt5M) {
        ElMessage.error('图片大小不能超过 5MB!')
        return false
    }
    return true
}

// 编辑用户
const handleEdit = (row: UserInfo) => {
    // 填充编辑表单数据
    Object.assign(editForm, {
        id: row.Id,
        account: row.Account || '',
        pwd: row.Pwd || '',
        name: row.Name || '',
        role: row.Role || '',
        isActive: row.IsActive,
        organizationStructure: row.OrganizationStructure || '',
        remark: row.Remark || '',
        avatar: row.Avatar || '',
        gender: row.Gender || '',
        singleSelectButton: row.SingleSelectButton,
        checkboxBull: row.CheckboxBull,
        checkboxCow: row.CheckboxCow,
        time: row.Time || '',
        date: row.Date || '',
        decimalValue: row.DecimalValue || 0,
        textArea: row.TextArea || '',
        image: row.Image || '',
        qqNumber2: row.QQNumber2 || '',
        qqNumber1: row.QQNumber1 || '',
        test: row.Test || '',
        test1: row.Test1 || ''
    })

    // 显示编辑弹框
    editDialogVisible.value = true
}

// 重置编辑表单
const resetEditForm = () => {
    Object.assign(editForm, {
        id: 0,
        account: '',
        pwd: '',
        name: '',
        role: '',
        isActive: true,
        organizationStructure: '',
        remark: '',
        avatar: '',
        gender: '',
        singleSelectButton: true,
        checkboxBull: true,
        checkboxCow: true,
        time: '',
        date: '',
        decimalValue: 0,
        textArea: '',
        image: '',
        qqNumber2: '',
        qqNumber1: '',
        test: '',
        test1: ''
    })
    if (editFormRef.value) {
        editFormRef.value.clearValidate()
    }
}

// 取消编辑
const handleEditCancel = () => {
    editDialogVisible.value = false
    resetEditForm()
}

// 提交编辑
const handleEditSubmit = async () => {
    try {
        // 先验证表单
        await editFormRef.value.validate()

        // 手动验证必填字段
        if (!editForm.account || editForm.account.trim() === '') {
            ElMessage.error('账户不能为空')
            return
        }
        if (!editForm.pwd || editForm.pwd.trim() === '') {
            ElMessage.error('密码不能为空')
            return
        }
        if (!editForm.name || editForm.name.trim() === '') {
            ElMessage.error('姓名不能为空')
            return
        }
        if (!editForm.role || editForm.role.trim() === '') {
            ElMessage.error('角色不能为空')
            return
        }
        if (!editForm.gender || editForm.gender.trim() === '') {
            ElMessage.error('性别不能为空')
            return
        }

        editLoading.value = true

        // 准备提交的数据
        const userData = {
            Id: editForm.id,
            Account: editForm.account?.trim() || '',
            Pwd: editForm.pwd?.trim() || '',
            Name: editForm.name?.trim() || '',
            Role: editForm.role?.trim() || '',
            IsActive: editForm.isActive,
            OrganizationStructure: editForm.organizationStructure?.trim() || '',
            Remark: editForm.remark?.trim() || '',
            Avatar: editForm.avatar?.trim() || '',
            Gender: editForm.gender?.trim() || '',
            SingleSelectButton: editForm.singleSelectButton,
            CheckboxBull: editForm.checkboxBull,
            CheckboxCow: editForm.checkboxCow,
            Time: formatTimeForSubmit(editForm.time),
            Date: formatDateForSubmit(editForm.date),
            DecimalValue: editForm.decimalValue || 0,
            TextArea: editForm.textArea?.trim() || '',
            Image: editForm.image?.trim() || '',
            QQNumber2: editForm.qqNumber2?.trim() || '',
            QQNumber1: editForm.qqNumber1?.trim() || '',
            Test: editForm.test?.trim() || '',
            Test1: editForm.test1?.trim() || ''
        }

        // 调用编辑接口
        const response = await MES_XHY_ApiHost.put('/api/Login/editUser', userData)

        if (response.data.code === 200) {
            ElMessage.success(response.data.msg || '用户信息更新成功')
            editDialogVisible.value = false
            resetEditForm()
            // 清空缓存数据，重新获取最新数据
            allUserList.value = []
            getUserList() // 刷新用户列表
        } else {
            ElMessage.error(response.data.msg || '用户信息更新失败')
        }
    } catch (error: any) {
        console.error('编辑用户失败:', error)

        // 处理不同类型的错误
        if (error.response) {
            const { status, data } = error.response
            if (status === 400) {
                ElMessage.error(data?.msg || '请求数据格式错误')
            } else if (status === 401) {
                ElMessage.error('未授权，请重新登录')
            } else if (status === 500) {
                ElMessage.error('服务器内部错误')
            } else {
                ElMessage.error(`请求失败: ${status}`)
            }
        } else if (error.request) {
            ElMessage.error('网络错误，请检查网络连接')
        } else {
            ElMessage.error(error.message || '编辑用户失败')
        }
    } finally {
        editLoading.value = false
    }
}

// 批量删除用户
const handleBatchDelete = async () => {
    if (selectedUsers.value.length === 0) {
        ElMessage.warning('请选择要删除的用户')
        return
    }

    try {
        await ElMessageBox.confirm(
            `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？`,
            '批量删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        batchDeleteLoading.value = true
        const userIds = selectedUsers.value.map(user => user.Id)

        // 使用POST方法，参数格式为UserIds
        const response = await MES_XHY_ApiHost.post('/api/Login/batchDeleteUsers', {
            UserIds: userIds
        })

        if (response.data.code === 200) {
            ElMessage.success(response.data.msg || '批量删除成功')
            // 清空选中数据
            selectedUsers.value = []
            // 清空缓存数据，重新获取最新数据
            allUserList.value = []
            // 刷新用户列表
            getUserList()
        } else {
            ElMessage.error(response.data.msg || '批量删除失败')
        }
    } catch (error: any) {
        console.error('批量删除失败:', error)

        // 处理不同类型的错误
        if (error.response) {
            const { status, data } = error.response
            if (status === 400) {
                ElMessage.error(data?.msg || '请求参数错误')
            } else if (status === 401) {
                ElMessage.error('未授权，请重新登录')
            } else if (status === 500) {
                ElMessage.error('服务器内部错误')
            } else {
                ElMessage.error(`请求失败: ${status}`)
            }
        } else if (error.request) {
            ElMessage.error('网络错误，请检查网络连接')
        } else {
            ElMessage.error(error.message || '批量删除失败')
        }
    } finally {
        batchDeleteLoading.value = false
    }
}

// 导出用户数据
const handleExport = async () => {
    try {
        exportLoading.value = true

        // 使用GET请求导出所有用户数据
        const response = await MES_XHY_ApiHost.get('/api/Login/exportUsers', {
            responseType: 'blob' // 设置响应类型为二进制流
        })

        // 创建Blob对象
        const blob = new Blob([response.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })

        // 生成文件名
        const fileName = `用户数据_${new Date().toISOString().slice(0, 10)}.xlsx`

        // 创建下载链接
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = fileName
        link.style.display = 'none'

        // 添加到DOM并触发下载
        document.body.appendChild(link)
        link.click()

        // 清理
        document.body.removeChild(link)
        URL.revokeObjectURL(link.href)

        ElMessage.success('用户数据导出成功')
    } catch (error: any) {
        console.error('导出用户数据失败:', error)

        // 处理不同类型的错误
        if (error.response) {
            const { status, data } = error.response
            if (status === 400) {
                ElMessage.error('请求参数错误')
            } else if (status === 401) {
                ElMessage.error('未授权，请重新登录')
            } else if (status === 500) {
                ElMessage.error('服务器内部错误')
            } else {
                ElMessage.error(`请求失败: ${status}`)
            }
        } else if (error.request) {
            ElMessage.error('网络错误，请检查网络连接')
        } else {
            ElMessage.error(error.message || '导出用户数据失败')
        }
    } finally {
        exportLoading.value = false
    }
}

// 导入用户数据
const handleImport = () => {
    importDialogVisible.value = true
    importFile.value = null
    importResult.value = null
}

// 下载导入模板
const downloadTemplate = async () => {
    try {
        const response = await MES_XHY_ApiHost.get('/api/Login/downloadImportTemplate', {
            responseType: 'blob'
        })

        // 创建Blob对象
        const blob = new Blob([response.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })

        // 生成文件名
        const fileName = `用户导入模板_${new Date().toISOString().slice(0, 10)}.xlsx`

        // 创建下载链接
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = fileName
        link.style.display = 'none'

        // 添加到DOM并触发下载
        document.body.appendChild(link)
        link.click()

        // 清理
        document.body.removeChild(link)
        URL.revokeObjectURL(link.href)

        ElMessage.success('导入模板下载成功')
    } catch (error: any) {
        console.error('下载导入模板失败:', error)
        ElMessage.error('下载导入模板失败')
    }
}

// 选择文件
const handleFileSelect = (event: Event) => {
    const target = event.target as HTMLInputElement
    if (target.files && target.files.length > 0) {
        importFile.value = target.files[0]
        console.log('选择的文件:', importFile.value.name, importFile.value.size)
    }
}

// 上传文件
const uploadFile = async () => {
    if (!importFile.value) {
        ElMessage.warning('请先选择要导入的文件')
        return
    }

    // 验证文件类型
    if (!importFile.value.name.endsWith('.xlsx') && !importFile.value.name.endsWith('.xls')) {
        ElMessage.error('只能上传Excel文件(.xlsx或.xls)')
        return
    }

    // 验证文件大小 (100MB = 100 * 1024 * 1024 bytes)
    if (importFile.value.size > 100 * 1024 * 1024) {
        ElMessage.error('文件大小不能超过100MB')
        return
    }

    try {
        importLoading.value = true

        // 创建FormData对象
        const formData = new FormData()
        formData.append('excelFile', importFile.value) // 使用后端期望的字段名 'excelFile'

        // 调试信息
        console.log('准备上传文件:', {
            fileName: importFile.value.name,
            fileSize: importFile.value.size,
            fileType: importFile.value.type
        })
        console.log('FormData内容:')
        for (let [key, value] of formData.entries()) {
            console.log(`${key}:`, value)
        }

        // 发送POST请求，添加查询参数
        const response = await MES_XHY_ApiHost.post('/api/Login/importUsers', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            params: {
                skipDuplicateAccount: true,  // 跳过重复账号
                updateExistingUser: false   // 不更新已存在的用户
            }
        })

        if (response.data.code === 200) {
            importResult.value = response.data.data
            ElMessage.success(response.data.msg)

            // 导入成功后刷新用户列表
            allUserList.value = []
            getUserList()
        } else {
            ElMessage.error(response.data.msg || '导入失败')
        }
    } catch (error: any) {
        console.error('导入用户数据失败:', error)

        if (error.response) {
            const { status, data } = error.response
            console.error('服务器响应错误:', { status, data })

            if (status === 400) {
                // 处理400错误，显示详细的验证错误信息
                if (data && data.errors) {
                    const errorMessages = Object.values(data.errors).flat()
                    ElMessage.error(`请求参数错误: ${errorMessages.join(', ')}`)
                } else if (data && data.title) {
                    ElMessage.error(data.title)
                } else {
                    ElMessage.error('请求参数错误，请检查文件格式和内容')
                }
            } else if (status === 401) {
                ElMessage.error('未授权，请重新登录')
            } else if (status === 500) {
                ElMessage.error('服务器内部错误')
            } else {
                ElMessage.error(`请求失败: ${status}`)
            }
        } else if (error.request) {
            ElMessage.error('网络错误，请检查网络连接')
        } else {
            ElMessage.error(error.message || '导入用户数据失败')
        }
    } finally {
        importLoading.value = false
    }
}

// 关闭导入弹框
const closeImportDialog = () => {
    importDialogVisible.value = false
    importFile.value = null
    importResult.value = null
}

// 触发文件选择
const triggerFileSelect = () => {
    const fileInput = document.getElementById('fileInput') as HTMLInputElement
    if (fileInput) {
        fileInput.click()
    }
}

// 列设置相关函数
const handleColumnSettings = () => {
    columnSettingsVisible.value = true
}

// 重置列设置
const resetColumnSettings = () => {
    Object.assign(columnSettings.columns, defaultColumnSettings)
    ElMessage.success('列设置已重置')
}

// 确认列设置
const confirmColumnSettings = () => {
    columnSettingsVisible.value = false
    ElMessage.success('列设置已保存')
}

// 获取可见的列
const getVisibleColumns = () => {
    return columnSettings.columns
        .filter(col => col.visible)
        .sort((a, b) => a.order - b.order)
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
    if (!dateTime) return '-'
    const date = new Date(dateTime)
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    })
}

// 格式化时间
const formatTime = (time: string) => {
    if (!time) return '-'
    const date = new Date(time)
    return date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    })
}

// 格式化日期
const formatDate = (date: string) => {
    if (!date) return '-'
    const dateObj = new Date(date)
    return dateObj.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
    })
}

// 图片加载错误处理
const handleImageError = (error: Event, imagePath?: string) => {
    console.error('图片加载失败:', error)
    if (imagePath) {
        console.error('失败的图片路径:', imagePath)
        console.error('尝试访问的完整URL:', getImageUrl(imagePath))

        // 建议：检查后端是否配置了静态文件服务
        console.warn('建议检查后端配置：')
        console.warn('1. 是否启用了 UseStaticFiles()')
        console.warn('2. wwwroot 目录是否正确配置')
        console.warn('3. 图片文件是否保存在正确位置')
    }
}

// 获取完整图片URL
const getImageUrl = (imagePath: string) => {
    if (!imagePath || imagePath === '//' || imagePath === '') {
        return ''
    }
    // 如果已经是完整URL，直接返回
    if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
        return imagePath
    }

    // 处理以斜杠开头的路径，避免双斜杠问题
    if (imagePath.startsWith('/')) {
        // 如果后端配置了静态文件服务，使用直接访问
        const directUrl = `${MES_XHY_ApiHost.defaults.baseURL}${imagePath}`

        // 临时方案：如果静态文件访问失败，可以通过API获取
        // 例如：/api/Login/getImage?path=${imagePath}
        // 这里先使用直接访问，如果失败再考虑API方式
        return directUrl
    }

    // 拼接完整的图片URL
    return `${MES_XHY_ApiHost.defaults.baseURL}/${imagePath}`
}

// 表格选择变化
const handleSelectionChange = (selection: UserInfo[]) => {
    selectedUsers.value = selection
}

// 页面加载时获取数据
onMounted(() => {
    console.log('页面加载，初始化分页配置:', pagination)
    console.log('开始加载用户数据...')
    getUserList()
})

// 测试前端分页功能
const testFrontendPagination = () => {
    console.log('=== 测试前端分页功能 ===')
    console.log('当前分页配置:', pagination)
    console.log('所有用户数据数量:', allUserList.value.length)
    console.log('当前页显示数据数量:', userList.value.length)
    console.log('分页信息显示:', {
        currentPage: pagination.currentPage,
        pageSize: pagination.pageSize,
        total: pagination.total,
        totalPages: Math.ceil(pagination.total / pagination.pageSize)
    })
    console.log('=======================')
}

// 格式化时间数据，确保符合后端要求
const formatTimeForSubmit = (timeValue: string | null) => {
    if (!timeValue) return null

    // 如果时间格式是 HH:mm:ss，转换为 ISO 格式
    if (timeValue.match(/^\d{2}:\d{2}:\d{2}$/)) {
        const today = new Date()
        const [hours, minutes, seconds] = timeValue.split(':')
        today.setHours(parseInt(hours), parseInt(minutes), parseInt(seconds))
        return today.toISOString()
    }

    return timeValue
}

// 格式化日期数据，确保符合后端要求
const formatDateForSubmit = (dateValue: string | null) => {
    if (!dateValue) return null

    // 如果日期格式是 YYYY-MM-DD，转换为 ISO 格式
    if (dateValue.match(/^\d{4}-\d{2}-\d{2}$/)) {
        const date = new Date(dateValue)
        return date.toISOString()
    }

    return dateValue
}
</script>

<style scoped>
.user-operation-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
    overflow-y: auto;
    scroll-behavior: smooth;
    -webkit-overflow-scrolling: touch;
    /* 为底部分页留出少量空间 */
    padding-bottom: 40px;
}

/* 取消容器缩放以保证 sticky 生效；保留其它紧凑化样式 */

/* 自定义滚动条样式 */
.user-operation-container::-webkit-scrollbar {
    width: 12px;
}

.user-operation-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 6px;
}

.user-operation-container::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 6px;
    border: 2px solid #f1f1f1;
}

.user-operation-container::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

.user-operation-container::-webkit-scrollbar-corner {
    background: #f1f1f1;
}

/* 响应式滚动优化 */
@media (max-width: 768px) {
    .user-operation-container::-webkit-scrollbar {
        width: 8px;
    }

    .user-operation-container {
        padding: 15px;
    }
}

/* 平滑滚动动画 */
.user-operation-container,
:deep(.el-table__body-wrapper) {
    scroll-behavior: smooth;
    transition: scroll-behavior 0.3s ease;
}

.query-section {
    margin-bottom: 12px;
}

.query-card {
    border-radius: 8px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
    color: #303133;
}

.header-actions {
    display: flex;
    gap: 6px;
}

.query-form {
    margin-bottom: 0;
}

.data-section {
    margin-bottom: 12px;
}

.data-card {
    border-radius: 8px;
    overflow: visible;
    /* 确保底部分页不被卡片裁剪 */
}

/* 卡片Body内边距更紧凑 */
:deep(.query-card .el-card__body),
:deep(.data-card .el-card__body) {
    padding: 12px 12px;
}

/* 表单项间距更紧凑 */
:deep(.el-form-item) {
    margin-bottom: 10px;
}

.pagination-container {
    margin-top: 12px;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 12px 0;
    position: static;
    /* 在列表下方显示 */
    background: transparent;
    border-top: 1px solid #ebeef5;
}

/* 分页组件样式优化 */
:deep(.el-pagination) {
    font-size: 14px;
}

:deep(.el-pagination .el-pager li) {
    margin: 0 2px;
}

:deep(.el-pagination .el-pager li.is-active) {
    background-color: #409eff;
    color: white;
}

:deep(.el-pagination .el-pager li:hover) {
    color: #409eff;
}

/* 分页信息样式 */
.pagination-info {
    margin: 15px 0 10px 0;
    text-align: center;
    color: #606266;
    font-size: 14px;
}

.pagination-text {
    background-color: #f5f7fa;
    padding: 8px 16px;
    border-radius: 4px;
    border: 1px solid #e4e7ed;
}

/* 空数据状态样式 */
.empty-data {
    margin: 40px 0;
    text-align: center;
}

.empty-data .el-empty {
    padding: 40px 0;
}

/* 导入功能样式 */
.import-container {
    padding: 20px 0;
}

.upload-area {
    text-align: center;
    padding: 30px;
    border: 2px dashed #d9d9d9;
    border-radius: 8px;
    background-color: #fafafa;
    margin-bottom: 20px;
}

.upload-buttons {
    display: flex;
    gap: 15px;
    justify-content: center;
    margin-bottom: 20px;
}

.file-info {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 10px;
    background-color: #f0f9ff;
    border: 1px solid #bae6fd;
    border-radius: 6px;
    color: #0369a1;
}

.file-size {
    color: #64748b;
    font-size: 12px;
}

.import-result {
    margin-top: 20px;
}

.result-details {
    text-align: left;
}

.result-details p {
    margin: 5px 0;
    font-size: 14px;
}

.success-count {
    color: #10b981;
    font-weight: bold;
}

.update-count {
    color: #3b82f6;
    font-weight: bold;
}

.skip-count {
    color: #f59e0b;
    font-weight: bold;
}

.failed-count {
    color: #ef4444;
    font-weight: bold;
}

.account-text {
    color: #409eff;
    font-weight: 500;
}

.text-truncate {
    display: inline-block;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

:deep(.el-table) {
    border-radius: 8px;
    font-size: 12px;
    /* 再次缩小表格字体 */
}

/* 紧凑表格：降低单元格内边距与行高 */
:deep(.compact-table .el-table__cell) {
    padding: 6px 8px;
}

:deep(.compact-table .cell) {
    line-height: 18px;
}

/* 列表头部按钮区域更紧凑 */
.header-actions :deep(.el-button) {
    padding: 6px 10px;
    font-size: 12px;
}

:deep(.el-table__body-wrapper) {
    overflow-x: auto;
    overflow-y: auto;
    min-width: 100%;
    scroll-behavior: smooth;
    -webkit-overflow-scrolling: touch;
    /* 限制表格体高度，内部滚动，保证分页在下方可见 */
    max-height: calc(100vh - 400px);
}

:deep(.el-table__body-wrapper::-webkit-scrollbar) {
    width: 8px;
    height: 8px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
    background: #f1f1f1;
    border-radius: 4px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
    background: #c1c1c1;
    border-radius: 4px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb:hover) {
    background: #a8a8a8;
}

:deep(.el-table th) {
    background-color: #fafafa;
    color: #606266;
    font-weight: 600;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
    background-color: #fafafa;
}

:deep(.el-card__header) {
    background-color: #f8f9fa;
    border-bottom: 1px solid #ebeef5;
}

:deep(.el-button) {
    border-radius: 6px;
}

:deep(.el-input__wrapper) {
    border-radius: 6px;
}

:deep(.el-tag) {
    border-radius: 4px;
}

:deep(.el-avatar) {
    border: 2px solid #f0f0f0;
}

.image-error {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 40px;
    color: #c0c4cc;
    font-size: 12px;
    background-color: #f5f7fa;
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
}

.image-error .el-icon {
    font-size: 16px;
    margin-bottom: 2px;
}

.image-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 40px;
    color: #c0c4cc;
    font-size: 12px;
    background-color: #fafafa;
    border: 1px dashed #e4e7ed;
    border-radius: 4px;
}

.image-placeholder .el-icon {
    font-size: 16px;
    margin-bottom: 2px;
}

/* 新增用户弹框样式 */
.dialog-footer {
    text-align: right;
}

.upload-container {
    display: flex;
    align-items: center;
    justify-content: center;
}

.upload-avatar {
    border: 2px solid #f0f0f0;
    cursor: pointer;
}

.upload-image {
    border: 2px solid #f0f0f0;
    cursor: pointer;
}

.upload-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 80px;
    height: 80px;
    color: #c0c4cc;
    font-size: 12px;
    background-color: #fafafa;
    border: 1px dashed #e4e7ed;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
}

.upload-placeholder:hover {
    border-color: #409eff;
    color: #409eff;
    background-color: #f0f9ff;
}

.upload-placeholder .el-icon {
    font-size: 24px;
    margin-bottom: 4px;
}

/* 编辑用户弹框样式 */
.dialog-footer {
    text-align: right;
}

:deep(.el-dialog__body) {
    padding: 20px;
}

:deep(.el-form-item__label) {
    font-weight: 500;
}

:deep(.el-switch__label) {
    font-size: 12px;
}
</style>
